/**
 * 沉浸式场景管理器
 * 统一管理场景加载、3D模型集成和WebXR交互
 */

import * as THREE from 'three';
import { ModelLoader } from './ModelLoader.js';
import { UnifiedXRManager } from './core/UnifiedXRManager.js';
import { CharacterLoader } from './loaders/CharacterLoader.js';
import { 
    getSceneConfig, 
    getPoetRecommendedScenes, 
    SCENE_TYPES,
    DEFAULT_SCENE 
} from './config/immersive-scenes-config.js';

export class ImmersiveSceneManager {
    constructor(renderer, scene = null, camera = null, options = {}) {
        this.renderer = renderer;
        this.options = {
            enableWebXR: options.enableWebXR !== false,
            enableShadows: options.enableShadows !== false,
            enablePostProcessing: options.enablePostProcessing !== false,
            ...options
        };

        // 核心Three.js组件 - 使用传入的或创建新的
        this.scene = scene || new THREE.Scene();
        this.camera = camera || new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this.clock = new THREE.Clock();

        // 场景组织
        this.sceneGroup = new THREE.Group();
        this.sceneGroup.name = 'immersive-scene';
        this.scene.add(this.sceneGroup);

        this.characterGroup = new THREE.Group();
        this.characterGroup.name = 'characters';
        this.scene.add(this.characterGroup);

        this.lightingGroup = new THREE.Group();
        this.lightingGroup.name = 'lighting';
        this.scene.add(this.lightingGroup);

        // 加载器和管理器
        this.modelLoader = new ModelLoader();
        this.characterLoader = new CharacterLoader({
            enableAnimations: true,
            enableShadows: this.options.enableShadows,
            optimizeForVR: this.options.enableWebXR
        });
        // Supersplat Viewer 覆盖层管理
        this.splatViewerContainer = null;
        this.splatViewerActive = false;
        this.webxrManager = null;

        // 状态管理
        this.currentScene = null;
        this.currentSceneId = null;
        this.loadedCharacters = new Map();
        this.isLoading = false;
        this.isVRMode = false;
        this.vrOptimizations = {
            enabled: false,
            lodEnabled: true,
            shadowQuality: 'medium',
            renderScale: 1.0,
            foveatedRendering: false
        };

        // VR性能管理
        this.vrPerformanceLevel = 'auto'; // auto, low, medium, high
        this.vrTargetFrameRate = 90; // VR标准帧率
        this.vrFrameTimeThreshold = 11.11; // 90fps = 11.11ms per frame

        // 事件系统
        this.eventListeners = new Map();

        // 初始化改为显式调用，避免并发初始化导致状态错乱
    }

    /**
     * 初始化场景管理器
     */
    async init() {
        // 设置渲染器
        this.setupRenderer();

        // 初始化WebXR（如果启用）
        if (this.options.enableWebXR) {
            this.webxrManager = new UnifiedXRManager(this.renderer, this.scene, this.camera, {
                enableHandTracking: true,
                enableHandModels: true,
                enableGestureRecognition: true,
                debugMode: false
            });
            await this.webxrManager.init();
        }

        // 设置默认相机位置
        this.camera.position.set(0, 1.6, 5);
        this.camera.lookAt(0, 1, 0);

        // 加载默认场景
        await this.loadScene(DEFAULT_SCENE);

        console.log('沉浸式场景管理器初始化完成');
    }

    /**
     * 设置渲染器
     */
    setupRenderer() {
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        
        if (this.options.enableShadows) {
            this.renderer.shadowMap.enabled = true;
            this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        }

        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.0;
        // 使画布默认透明，便于与外部Viewer叠加
        this.renderer.setClearAlpha(0);
        if (this.renderer?.domElement) {
            this.renderer.domElement.style.background = 'transparent';
        }
    }

    /**
     * 加载场景
     * @param {string} sceneId - 场景ID
     * @param {Object} options - 加载选项
     */
    async loadScene(sceneId, options = {}) {
        if (this.isLoading) {
            console.warn('场景正在加载中，请稍候');
            return false;
        }

        try {
            this.isLoading = true;
            this.dispatchEvent('sceneLoadStart', { sceneId });

            const sceneConfig = getSceneConfig(sceneId);
            if (!sceneConfig) {
                throw new Error(`场景配置未找到: ${sceneId}`);
            }

            console.log(`开始加载场景: ${sceneConfig.name}`);

            // 添加淡出效果
            await this.fadeOut();

            // 清理当前场景
            await this.clearCurrentScene();

            // 根据场景类型加载
            let success = false;
            switch (sceneConfig.type) {
                case SCENE_TYPES.GLTF:
                    success = await this.loadGLTFScene(sceneConfig);
                    break;
                case SCENE_TYPES.SUPERSPLAT_VIEWER:
                    success = await this.loadSupersplatViewerScene(sceneConfig);
                    break;
                case SCENE_TYPES.PROCEDURAL:
                    success = await this.loadProceduralScene(sceneConfig);
                    break;
                case SCENE_TYPES.HYBRID:
                    success = await this.loadHybridScene(sceneConfig);
                    break;
                default:
                    throw new Error(`不支持的场景类型: ${sceneConfig.type}`);
            }

            if (success) {
                // 设置场景环境
                this.setupSceneEnvironment(sceneConfig);
                
                // 设置光照
                this.setupSceneLighting(sceneConfig);
                
                // 设置相机
                this.setupSceneCamera(sceneConfig);

                this.currentScene = sceneConfig;
                this.currentSceneId = sceneId;

                // 添加淡入效果
                await this.fadeIn();

                console.log(`场景加载完成: ${sceneConfig.name}`);
                this.dispatchEvent('sceneLoadComplete', { sceneId, sceneConfig });
                
                return true;
            } else {
                throw new Error('场景加载失败');
            }

        } catch (error) {
            console.error('场景加载错误:', error);
            // 确保在错误时也恢复透明度
            await this.fadeIn();
            this.dispatchEvent('sceneLoadError', { sceneId, error });
            return false;
        } finally {
            this.isLoading = false;
        }
    }

    /**
     * 加载GLTF场景
     * @param {Object} sceneConfig - 场景配置
     */
    async loadGLTFScene(sceneConfig) {
        try {
            const modelData = await this.modelLoader.loadModel(sceneConfig.sceneFile, {
                castShadow: this.options.enableShadows,
                receiveShadow: this.options.enableShadows
            });

            this.sceneGroup.add(modelData.model);
            return true;
        } catch (error) {
            console.error('GLTF场景加载失败:', error);
            return false;
        }
    }

    /**
     * 加载3DGS场景
     * @param {Object} sceneConfig - 场景配置
     */
    /**
     * 加载 Supersplat Viewer 场景（以覆盖层 iframe 方式集成）
     */
    async loadSupersplatViewerScene(sceneConfig) {
        try {
            console.log('加载 Supersplat Viewer 场景:', sceneConfig.name);
            const plyUrl = new URL(sceneConfig.sceneFile, window.location.origin).href;
            const viewerUrl = `/supersplat-viewer-local/index.html?content=${encodeURIComponent(plyUrl)}&ministats=true`;

            // 创建并显示覆盖层
            this.createSplatViewerOverlay(viewerUrl);
            this.splatViewerActive = true;

            // 显示Three.js主渲染Canvas作为角色叠加层（透明、置于overlay之上）
            if (this.renderer?.domElement) {
                const canvas = this.renderer.domElement;
                canvas.style.display = 'block';
                canvas.style.position = 'fixed';
                canvas.style.top = '0';
                canvas.style.left = '0';
                canvas.style.width = '100vw';
                canvas.style.height = '100vh';
                canvas.style.zIndex = '30'; // 高于 viewer overlay，低于主UI
                canvas.style.pointerEvents = 'none'; // 让 viewer 的交互不被阻挡
            }

            // 保持Three场景透明
            this.scene.background = null;

            await new Promise((resolve) => setTimeout(resolve, 300));

            this.dispatchEvent('sceneLoaded', {
                sceneId: sceneConfig.id,
                sceneType: 'supersplat_viewer',
                viewerUrl
            });
            return true;
        } catch (error) {
            console.error('Supersplat Viewer 场景加载失败:', error);
            this.dispatchEvent('sceneLoadError', { sceneId: sceneConfig.id, error: error.message });
            return false;
        }
    }

    /**
     * 加载程序化场景
     * @param {Object} sceneConfig - 场景配置
     */
    async loadProceduralScene(sceneConfig) {
        try {
            const generator = this.getProceduralGenerator(sceneConfig.generator);
            if (!generator) {
                throw new Error(`程序化生成器未找到: ${sceneConfig.generator}`);
            }

            const generatedScene = await generator(sceneConfig.parameters);
            this.sceneGroup.add(generatedScene);
            return true;
        } catch (error) {
            console.error('程序化场景生成失败:', error);
            return false;
        }
    }

    /**
     * 加载混合场景
     * @param {Object} sceneConfig - 场景配置
     */
    async loadHybridScene(sceneConfig) {
        try {
            for (const component of sceneConfig.components) {
                let success = false;
                
                switch (component.type) {
                    case SCENE_TYPES.GLTF:
                        const modelData = await this.modelLoader.loadModel(component.file);
                        if (component.position) {
                            modelData.model.position.copy(component.position);
                        }
                        this.sceneGroup.add(modelData.model);
                        success = true;
                        break;
                        
                    case SCENE_TYPES.GAUSSIAN_SPLAT:
                        console.warn('GAUSSIAN_SPLAT 类型已停用，跳过组件:', component.file);
                        success = false;
                        break;
                }

                if (!success) {
                    console.warn(`混合场景组件加载失败: ${component.file}`);
                }
            }
            return true;
        } catch (error) {
            console.error('混合场景加载失败:', error);
            return false;
        }
    }

    /**
     * 在场景中加载3D角色
     * @param {string} characterId - 角色ID
     * @param {string} modelPath - 模型文件路径
     * @param {Object} options - 加载选项
     */
    async loadCharacter(characterId, modelPath, options = {}) {
        try {
            console.log(`加载3D角色: ${characterId}`);

            // 在添加新角色前移除占位符（如胶囊体）以避免重叠
            if (this.characterGroup && this.characterGroup.children?.length) {
                this.characterGroup.children.slice().forEach(child => {
                    if (child?.userData && (child.userData.isPlaceholder === true || child.userData.isCharacter === true && child.userData.isPlaceholder)) {
                        this.characterGroup.remove(child);
                    }
                });
            }

            // 获取角色生成位置
            const spawnPoint = this.currentScene?.characterSpawnPoint || { x: 0, y: 0, z: -3 };
            console.log('角色生成位置:', spawnPoint);

            // 使用标准加载路径（3DGS集成已停用）
            console.log('加载角色（标准场景）');
            const modelData = await this.modelLoader.loadModel(modelPath, {
                castShadow: this.options.enableShadows,
                receiveShadow: false,
                ...options
            });
            // 设置角色位置
            modelData.model.position.set(spawnPoint.x, spawnPoint.y, spawnPoint.z);

            console.log('角色实际位置:', modelData.model.position);

            // 添加到角色组
            this.characterGroup.add(modelData.model);

            // 缓存角色数据
            this.loadedCharacters.set(characterId, {
                model: modelData.model,
                animations: modelData.animations,
                animationController: modelData.animationController
            });

            // 默认显示刚加载的角色，隐藏其他角色以避免叠加
            this.switchCharacter(characterId);

            this.dispatchEvent('characterLoaded', { characterId, modelData });
            
            console.log(`3D角色加载完成: ${characterId}`);
            return modelData;

        } catch (error) {
            console.error(`角色加载失败 ${characterId}:`, error);
            this.dispatchEvent('characterLoadError', { characterId, error });
            return null;
        }
    }

    /**
     * 切换角色
     * @param {string} characterId - 角色ID
     */
    switchCharacter(characterId) {
        // 隐藏所有角色
        this.characterGroup.children.forEach(child => {
            child.visible = false;
        });

        // 显示指定角色
        const characterData = this.loadedCharacters.get(characterId);
        if (characterData) {
            characterData.model.visible = true;
            this.dispatchEvent('characterSwitched', { characterId });
            return true;
        }

        console.warn(`角色未找到: ${characterId}`);
        return false;
    }

    /**
     * 播放角色动画
     * @param {string} characterId - 角色ID
     * @param {string} animationName - 动画名称
     * @param {Object} options - 动画选项
     */
    playCharacterAnimation(characterId, animationName, options = {}) {
        const characterData = this.loadedCharacters.get(characterId);
        if (characterData && characterData.animationController) {
            return characterData.animationController.playAnimation(animationName, options);
        }
        return false;
    }

    /**
     * 设置场景环境
     * @param {Object} sceneConfig - 场景配置
     */
    setupSceneEnvironment(sceneConfig) {
        if (sceneConfig.environment) {
            const env = sceneConfig.environment;
            
            // 设置背景：Supersplat 场景保持透明，不设置背景色
            if (env.background !== undefined) {
                if (this.splatViewerActive || sceneConfig.type === SCENE_TYPES.SUPERSPLAT_VIEWER) {
                    this.scene.background = null;
                    this.renderer.setClearAlpha(0);
                } else {
                    this.scene.background = new THREE.Color(env.background);
                }
            }

            // 设置雾效
            if (env.fog) {
                this.scene.fog = new THREE.Fog(env.fog.color, env.fog.near, env.fog.far);
            }
        }
    }

    /**
     * 设置场景光照
     * @param {Object} sceneConfig - 场景配置
     */
    setupSceneLighting(sceneConfig) {
        // 清理现有光照
        this.lightingGroup.clear();

        if (!sceneConfig.lighting) return;

        const lighting = sceneConfig.lighting;

        // 环境光
        if (lighting.ambient) {
            const ambientLight = new THREE.AmbientLight(
                lighting.ambient.color, 
                lighting.ambient.intensity
            );
            this.lightingGroup.add(ambientLight);
        }

        // 方向光
        if (lighting.directional) {
            const dirLight = new THREE.DirectionalLight(
                lighting.directional.color,
                lighting.directional.intensity
            );
            
            if (lighting.directional.position) {
                dirLight.position.set(
                    lighting.directional.position.x,
                    lighting.directional.position.y,
                    lighting.directional.position.z
                );
            }

            if (lighting.directional.castShadow && this.options.enableShadows) {
                dirLight.castShadow = true;
                dirLight.shadow.mapSize.width = 2048;
                dirLight.shadow.mapSize.height = 2048;
                dirLight.shadow.camera.near = 0.5;
                dirLight.shadow.camera.far = 50;
                dirLight.shadow.camera.left = -10;
                dirLight.shadow.camera.right = 10;
                dirLight.shadow.camera.top = 10;
                dirLight.shadow.camera.bottom = -10;
            }

            this.lightingGroup.add(dirLight);
        }

        // 点光源
        if (lighting.point && Array.isArray(lighting.point)) {
            lighting.point.forEach(pointConfig => {
                const pointLight = new THREE.PointLight(
                    pointConfig.color,
                    pointConfig.intensity,
                    pointConfig.distance || 0
                );
                
                if (pointConfig.position) {
                    pointLight.position.set(
                        pointConfig.position.x,
                        pointConfig.position.y,
                        pointConfig.position.z
                    );
                }

                this.lightingGroup.add(pointLight);
            });
        }
    }

    /**
     * 设置场景相机
     * @param {Object} sceneConfig - 场景配置
     */
    setupSceneCamera(sceneConfig) {
        if (sceneConfig.cameraPosition) {
            this.camera.position.set(
                sceneConfig.cameraPosition.x,
                sceneConfig.cameraPosition.y,
                sceneConfig.cameraPosition.z
            );
        }

        if (sceneConfig.cameraTarget) {
            this.camera.lookAt(
                sceneConfig.cameraTarget.x,
                sceneConfig.cameraTarget.y,
                sceneConfig.cameraTarget.z
            );
        }

        // 3DGS自动框选路径已停用
    }

    /**
     * 处理XR模式切换
     * @param {boolean} isXRActive - XR模式是否激活
     */
    onXRModeChange(isXRActive) {
        console.log(`🔄 XR模式切换: ${isXRActive ? '激活' : '停用'}`);
        
        // 更新状态
        this.isVRMode = isXRActive;
        
        // 根据XR模式调整性能设置
        this.updateVROptimizations(isXRActive);
        
        // 触发XR模式变化事件
        this.dispatchEvent('xrModeChange', { isXRActive });
        
        // 如果有角色在场景中，更新其状态
        this.updateCharactersForXRMode(isXRActive);
    }
    
    /**
     * 更新VR优化设置
     */
    updateVROptimizations(isXRActive) {
        if (isXRActive) {
            // XR模式下启用优化
            this.vrOptimizations.enabled = true;
            console.log('✅ 启用VR性能优化');
            
            // 可以在这里调整渲染参数
            if (this.renderer) {
                // 根据性能级别调整渲染设置
                switch (this.vrPerformanceLevel) {
                    case 'low':
                        this.renderer.toneMapping = THREE.LinearToneMapping;
                        this.vrOptimizations.renderScale = 0.8;
                        break;
                    case 'medium':
                        this.renderer.toneMapping = THREE.ReinhardToneMapping;
                        this.vrOptimizations.renderScale = 0.9;
                        break;
                    case 'high':
                    case 'auto':
                    default:
                        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
                        this.vrOptimizations.renderScale = 1.0;
                        break;
                }
            }
        } else {
            // 非XR模式下禁用特定优化
            this.vrOptimizations.enabled = false;
            console.log('✅ 恢复标准渲染设置');
        }
    }
    
    /**
     * 更新角色以适应XR模式
     */
    updateCharactersForXRMode(isXRActive) {
        if (this.loadedCharacters.size > 0) {
            this.loadedCharacters.forEach(character => {
                if (character && typeof character.updateForXRMode === 'function') {
                    character.updateForXRMode(isXRActive);
                }
            });
        }
    }
    
    /**
     * 清理当前场景
     */
    async clearCurrentScene() {
        // 清理场景组
        this.sceneGroup.clear();
        
        // 清理光照
        this.lightingGroup.clear();
        
        // 额外清理：角色组与角色缓存，避免场景切换后重复或残留
        if (this.characterGroup) {
            this.characterGroup.clear();
        }
        if (this.loadedCharacters && typeof this.loadedCharacters.clear === 'function') {
            this.loadedCharacters.clear();
        }
        
        // 销毁 Supersplat Viewer 覆盖层并恢复主渲染器显示
        this.destroySplatViewerOverlay();
        this.splatViewerActive = false;
        if (this.renderer?.domElement) {
            const canvas = this.renderer.domElement;
            canvas.style.display = '';
            canvas.style.position = '';
            canvas.style.top = '';
            canvas.style.left = '';
            canvas.style.width = '';
            canvas.style.height = '';
            canvas.style.zIndex = '';
            canvas.style.pointerEvents = '';
        }

        // 重置场景属性
        this.scene.background = null;
        this.scene.fog = null;
        // 恢复清屏不透明度（由后续环境决定背景是否可见）
        this.renderer.setClearAlpha(1);

        this.currentScene = null;
        this.currentSceneId = null;
    }

    /**
     * 获取程序化生成器
     * @param {string} generatorType - 生成器类型
     */
    getProceduralGenerator(generatorType) {
        const generators = {
            garden: this.generateGarden.bind(this),
            // 可以添加更多生成器
        };
        return generators[generatorType];
    }

    /**
     * 生成花园场景
     * @param {Object} params - 生成参数
     */
    async generateGarden(params) {
        const group = new THREE.Group();
        
        // 创建地面
        const groundGeometry = new THREE.PlaneGeometry(params.size.width, params.size.depth);
        const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x4a7c59 });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        group.add(ground);

        // 添加树木
        for (let i = 0; i < params.treeCount; i++) {
            const tree = this.createSimpleTree();
            tree.position.set(
                (Math.random() - 0.5) * params.size.width * 0.8,
                0,
                (Math.random() - 0.5) * params.size.depth * 0.8
            );
            group.add(tree);
        }

        return group;
    }

    /**
     * 创建简单树木
     */
    createSimpleTree() {
        const group = new THREE.Group();
        
        // 树干
        const trunkGeometry = new THREE.CylinderGeometry(0.1, 0.15, 2);
        const trunkMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
        trunk.position.y = 1;
        trunk.castShadow = true;
        group.add(trunk);

        // 树冠
        const crownGeometry = new THREE.SphereGeometry(1.5);
        const crownMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 });
        const crown = new THREE.Mesh(crownGeometry, crownMaterial);
        crown.position.y = 2.5;
        crown.castShadow = true;
        group.add(crown);

        return group;
    }

    /**
     * 进入WebXR模式
     * @param {string} mode - XR模式 ('vr' 或 'ar')
     */
    async enterXR(mode = 'vr') {
        if (this.webxrManager) {
            const success = await this.webxrManager.startXRSession(mode);
            if (success) {
                this.isVRMode = true;
                await this.enableVROptimizations();
                this.dispatchEvent('vrModeEntered', { mode });
            }
            return success;
        }
        console.warn('WebXR未启用');
        return false;
    }

    /**
     * 退出WebXR模式
     */
    async exitXR() {
        if (this.webxrManager) {
            const success = await this.webxrManager.endXRSession();
            if (success) {
                this.isVRMode = false;
                await this.disableVROptimizations();
                this.dispatchEvent('vrModeExited');
            }
            return success;
        }
        return false;
    }

    /**
     * 启用VR优化
     */
    async enableVROptimizations() {
        console.log('启用VR优化...');
        
        this.vrOptimizations.enabled = true;
        
        // 调整渲染器设置
        this.optimizeRendererForVR();
        
        // 优化场景对象
        this.optimizeSceneForVR();
        
        // 调整光照
        this.optimizeLightingForVR();
        
        // 启用LOD
        if (this.vrOptimizations.lodEnabled) {
            this.enableLODForVR();
        }
        
        // 调整阴影质量
        this.adjustShadowQualityForVR();
        
        console.log('VR优化已启用');
    }

    /**
     * 禁用VR优化
     */
    async disableVROptimizations() {
        console.log('禁用VR优化...');
        
        this.vrOptimizations.enabled = false;
        
        // 恢复原始渲染器设置
        this.restoreOriginalRendererSettings();
        
        // 恢复场景设置
        this.restoreOriginalSceneSettings();
        
        console.log('VR优化已禁用');
    }

    /**
     * 为VR优化渲染器
     */
    optimizeRendererForVR() {
        // 设置VR特定的渲染参数
        this.renderer.xr.enabled = true;
        
        // 调整像素比例以提高性能
        const vrPixelRatio = Math.min(window.devicePixelRatio, 1.5);
        this.renderer.setPixelRatio(vrPixelRatio);
        
        // 启用多重采样抗锯齿
        if (this.renderer.capabilities.isWebGL2) {
            this.renderer.antialias = true;
        }
        
        // 优化色彩空间
        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        
        // 调整色调映射
        this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        this.renderer.toneMappingExposure = 1.2;
    }

    /**
     * 为VR优化场景
     */
    optimizeSceneForVR() {
        // 遍历场景中的所有对象进行优化
        this.scene.traverse((object) => {
            if (object.isMesh) {
                this.optimizeMeshForVR(object);
            }
        });
        
        // 启用视锥体剔除
        this.enableFrustumCulling();
        
        // 优化材质
        this.optimizeMaterialsForVR();
    }

    /**
     * 为VR优化网格对象
     */
    optimizeMeshForVR(mesh) {
        // 简化几何体（如果顶点数过多）
        if (mesh.geometry && mesh.geometry.attributes.position) {
            const vertexCount = mesh.geometry.attributes.position.count;
            if (vertexCount > 10000) {
                // 可以在这里添加几何体简化逻辑
                console.log(`网格 ${mesh.name} 顶点数较多 (${vertexCount})，考虑简化`);
            }
        }
        
        // 启用阴影（如果适当）
        if (this.vrOptimizations.shadowQuality !== 'off') {
            mesh.castShadow = true;
            mesh.receiveShadow = true;
        }
        
        // 设置渲染顺序
        if (mesh.material && mesh.material.transparent) {
            mesh.renderOrder = 1;
        }
    }

    /**
     * 为VR优化光照
     */
    optimizeLightingForVR() {
        this.lightingGroup.children.forEach(light => {
            if (light.isDirectionalLight) {
                // 调整方向光阴影设置
                if (light.castShadow) {
                    this.optimizeDirectionalLightShadow(light);
                }
            } else if (light.isPointLight) {
                // 优化点光源
                this.optimizePointLight(light);
            }
        });
    }

    /**
     * 优化方向光阴影
     */
    optimizeDirectionalLightShadow(light) {
        const shadowQuality = this.vrOptimizations.shadowQuality;
        
        switch (shadowQuality) {
            case 'low':
                light.shadow.mapSize.setScalar(512);
                break;
            case 'medium':
                light.shadow.mapSize.setScalar(1024);
                break;
            case 'high':
                light.shadow.mapSize.setScalar(2048);
                break;
            default:
                light.shadow.mapSize.setScalar(1024);
        }
        
        // 优化阴影相机
        light.shadow.camera.near = 0.1;
        light.shadow.camera.far = 25;
        light.shadow.bias = -0.0001;
    }

    /**
     * 优化点光源
     */
    optimizePointLight(light) {
        // 限制点光源的影响范围以提高性能
        if (!light.distance || light.distance > 20) {
            light.distance = 20;
        }
        
        // 调整衰减
        light.decay = 2;
    }

    /**
     * 启用视锥体剔除
     */
    enableFrustumCulling() {
        // Three.js默认启用视锥体剔除，这里可以添加自定义逻辑
        this.scene.traverse((object) => {
            if (object.isMesh) {
                object.frustumCulled = true;
            }
        });
    }

    /**
     * 为VR优化材质
     */
    optimizeMaterialsForVR() {
        this.scene.traverse((object) => {
            if (object.isMesh && object.material) {
                this.optimizeMaterialForVR(object.material);
            }
        });
    }

    /**
     * 优化单个材质
     */
    optimizeMaterialForVR(material) {
        if (Array.isArray(material)) {
            material.forEach(mat => this.optimizeMaterialForVR(mat));
            return;
        }
        
        // 禁用不必要的特性以提高性能
        if (material.isMeshStandardMaterial || material.isMeshPhysicalMaterial) {
            // 简化材质设置
            material.roughness = Math.max(material.roughness, 0.1);
            material.metalness = Math.min(material.metalness, 0.9);
        }
        
        // 优化纹理设置
        if (material.map) {
            this.optimizeTextureForVR(material.map);
        }
        if (material.normalMap) {
            this.optimizeTextureForVR(material.normalMap);
        }
        if (material.roughnessMap) {
            this.optimizeTextureForVR(material.roughnessMap);
        }
    }

    /**
     * 为VR优化纹理
     */
    optimizeTextureForVR(texture) {
        // 设置合适的过滤方式
        texture.minFilter = THREE.LinearMipmapLinearFilter;
        texture.magFilter = THREE.LinearFilter;
        
        // 启用各向异性过滤（适度）
        texture.anisotropy = Math.min(4, this.renderer.capabilities.getMaxAnisotropy());
        
        // 确保纹理格式优化
        if (texture.format === THREE.RGBAFormat && !texture.transparent) {
            texture.format = THREE.RGBFormat;
        }
    }

    /**
     * 为VR启用LOD
     */
    enableLODForVR() {
        // 为复杂对象创建LOD
        this.scene.traverse((object) => {
            if (object.isMesh && this.shouldUseLOD(object)) {
                this.createLODForObject(object);
            }
        });
    }

    /**
     * 判断对象是否应该使用LOD
     */
    shouldUseLOD(object) {
        if (!object.geometry || !object.geometry.attributes.position) {
            return false;
        }
        
        const vertexCount = object.geometry.attributes.position.count;
        return vertexCount > 5000; // 超过5000个顶点的对象使用LOD
    }

    /**
     * 为对象创建LOD
     */
    createLODForObject(object) {
        const lod = new THREE.LOD();
        
        // 高细节级别（原始对象）
        lod.addLevel(object, 0);
        
        // 中等细节级别（可以在这里添加简化版本）
        // const mediumDetail = this.createSimplifiedMesh(object, 0.5);
        // lod.addLevel(mediumDetail, 10);
        
        // 低细节级别
        // const lowDetail = this.createSimplifiedMesh(object, 0.25);
        // lod.addLevel(lowDetail, 25);
        
        // 替换原始对象
        if (object.parent) {
            object.parent.add(lod);
            object.parent.remove(object);
        }
    }

    /**
     * 调整VR阴影质量
     */
    adjustShadowQualityForVR() {
        const shadowQuality = this.vrOptimizations.shadowQuality;
        
        if (shadowQuality === 'off') {
            this.renderer.shadowMap.enabled = false;
        } else {
            this.renderer.shadowMap.enabled = true;
            
            switch (shadowQuality) {
                case 'low':
                    this.renderer.shadowMap.type = THREE.BasicShadowMap;
                    break;
                case 'medium':
                    this.renderer.shadowMap.type = THREE.PCFShadowMap;
                    break;
                case 'high':
                    this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
                    break;
                default:
                    this.renderer.shadowMap.type = THREE.PCFShadowMap;
            }
        }
    }

    /**
     * 恢复原始渲染器设置
     */
    restoreOriginalRendererSettings() {
        // 恢复原始像素比例
        this.renderer.setPixelRatio(window.devicePixelRatio);
        
        // 恢复原始色调映射
        this.renderer.toneMappingExposure = 1.0;
    }

    /**
     * 恢复原始场景设置
     */
    restoreOriginalSceneSettings() {
        // 恢复阴影设置
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        
        // 可以在这里添加更多恢复逻辑
    }

    /**
     * 设置VR性能级别
     */
    setVRPerformanceLevel(level) {
        this.vrPerformanceLevel = level;
        
        switch (level) {
            case 'low':
                this.vrOptimizations.shadowQuality = 'off';
                this.vrOptimizations.renderScale = 0.8;
                this.vrOptimizations.lodEnabled = true;
                break;
            case 'medium':
                this.vrOptimizations.shadowQuality = 'low';
                this.vrOptimizations.renderScale = 0.9;
                this.vrOptimizations.lodEnabled = true;
                break;
            case 'high':
                this.vrOptimizations.shadowQuality = 'medium';
                this.vrOptimizations.renderScale = 1.0;
                this.vrOptimizations.lodEnabled = false;
                break;
            case 'auto':
                this.autoDetectVRPerformanceLevel();
                break;
        }
        
        // 如果当前在VR模式，重新应用优化
        if (this.isVRMode) {
            this.enableVROptimizations();
        }
    }

    /**
     * 自动检测VR性能级别
     */
    autoDetectVRPerformanceLevel() {
        // 基于设备性能自动选择合适的性能级别
        const gl = this.renderer.getContext();
        const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
        
        if (debugInfo) {
            const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
            
            // 简单的GPU性能检测
            if (renderer.includes('Apple') || renderer.includes('M1') || renderer.includes('M2')) {
                this.setVRPerformanceLevel('high');
            } else if (renderer.includes('RTX') || renderer.includes('GTX')) {
                this.setVRPerformanceLevel('medium');
            } else {
                this.setVRPerformanceLevel('low');
            }
        } else {
            // 默认使用中等性能
            this.setVRPerformanceLevel('medium');
        }
    }

    /**
     * 更新场景
     */
    update() {
        const deltaTime = this.clock.getDelta();
        const currentTime = performance.now();

        // VR性能监控
        if (this.isVRMode) {
            this.monitorVRPerformance(deltaTime, currentTime);
        }

        // 更新角色动画
        this.loadedCharacters.forEach(characterData => {
            if (characterData.animationController) {
                characterData.animationController.update();
            }
        });

        // 3DGS环境更新已停用

        // 更新WebXR
        if (this.webxrManager) {
            this.webxrManager.update();
        }

        // 更新LOD（如果启用）
        if (this.isVRMode && this.vrOptimizations.lodEnabled) {
            this.updateLOD();
        }
    }

    /**
     * 监控VR性能
     */
    monitorVRPerformance(deltaTime, currentTime) {
        // 计算帧时间
        const frameTime = deltaTime * 1000; // 转换为毫秒
        
        // 检查是否低于目标帧率
        if (frameTime > this.vrFrameTimeThreshold) {
            this.handleLowFrameRate(frameTime);
        }
        
        // 每秒检查一次性能
        if (!this.lastPerformanceCheck) {
            this.lastPerformanceCheck = currentTime;
            this.frameTimeHistory = [];
        }
        
        this.frameTimeHistory.push(frameTime);
        
        if (currentTime - this.lastPerformanceCheck > 1000) { // 每秒检查
            this.analyzePerformance();
            this.lastPerformanceCheck = currentTime;
            this.frameTimeHistory = [];
        }
    }

    /**
     * 处理低帧率情况
     */
    handleLowFrameRate(frameTime) {
        const currentTime = Date.now();
        
        // 添加警告频率限制，每10秒最多显示一次警告
        if (!this.lastLowFrameRateWarning || (currentTime - this.lastLowFrameRateWarning > 10000)) {
            console.warn(`VR帧率过低: ${frameTime.toFixed(2)}ms (目标: ${this.vrFrameTimeThreshold.toFixed(2)}ms)`);
            this.lastLowFrameRateWarning = currentTime;
        }
        
        // 自动降低性能级别
        if (this.vrPerformanceLevel === 'high') {
            this.setVRPerformanceLevel('medium');
        } else if (this.vrPerformanceLevel === 'medium') {
            this.setVRPerformanceLevel('low');
        }
    }

    /**
     * 分析性能数据
     */
    analyzePerformance() {
        if (this.frameTimeHistory.length === 0) return;
        
        const avgFrameTime = this.frameTimeHistory.reduce((a, b) => a + b, 0) / this.frameTimeHistory.length;
        const maxFrameTime = Math.max(...this.frameTimeHistory);
        
        console.log(`VR性能统计 - 平均帧时间: ${avgFrameTime.toFixed(2)}ms, 最大帧时间: ${maxFrameTime.toFixed(2)}ms`);
        
        // 如果性能良好，可以尝试提升质量
        if (avgFrameTime < this.vrFrameTimeThreshold * 0.8 && maxFrameTime < this.vrFrameTimeThreshold) {
            this.considerPerformanceUpgrade();
        }
    }

    /**
     * 考虑性能升级
     */
    considerPerformanceUpgrade() {
        if (this.vrPerformanceLevel === 'low') {
            this.setVRPerformanceLevel('medium');
        } else if (this.vrPerformanceLevel === 'medium') {
            this.setVRPerformanceLevel('high');
        }
    }

    /**
     * 更新LOD
     */
    updateLOD() {
        // 获取相机位置
        const cameraPosition = this.camera.position;
        
        // 更新所有LOD对象
        this.scene.traverse((object) => {
            if (object.isLOD) {
                object.update(this.camera);
            }
        });
    }

    /**
     * 渲染场景
     */
    render() {
        this.renderer.render(this.scene, this.camera);
    }

    /**
     * 创建 Supersplat Viewer 覆盖层
     */
    createSplatViewerOverlay(viewerUrl) {
        // 如果已存在则先销毁
        this.destroySplatViewerOverlay();
        
        const container = document.createElement('div');
        container.id = 'supersplat-viewer-overlay';
        container.style.position = 'fixed';
        container.style.top = '0';
        container.style.left = '0';
        container.style.width = '100vw';
        container.style.height = '100vh';
        // 将覆盖层置于主界面 UI 之后，保持主面板可见
        container.style.zIndex = '20';
        container.style.background = '#000';
        container.style.display = 'block';

        const iframe = document.createElement('iframe');
        iframe.src = viewerUrl;
        iframe.style.width = '100%';
        iframe.style.height = '100%';
        iframe.style.border = '0';
        iframe.allow = 'camera; microphone; clipboard-read; clipboard-write; xr-spatial-tracking';
        
        container.appendChild(iframe);

        // 不再在覆盖层中创建独立的诗人选择器面板，直接复用主界面 UI
        document.body.appendChild(container);
        this.splatViewerContainer = container;

        // 保存 iframe 引用，并开启来自 Viewer 的相机位姿同步
        this.splatViewerIframe = iframe;
        // 清理旧的监听器，避免重复绑定
        if (this._onSplatViewerMessage) {
            window.removeEventListener('message', this._onSplatViewerMessage);
            this._onSplatViewerMessage = null;
        }
        this._onSplatViewerMessage = (event) => {
            try {
                const data = event?.data;
                if (!data) return;
                if (data.type === 'splatCameraPose' && data.payload) {
                    const { position, quaternion, fov, isHorizontalFov, aspect } = data.payload;
                    if (position && this.camera) {
                        this.camera.position.set(position.x, position.y, position.z);
                    }
                    if (quaternion && this.camera) {
                        this.camera.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
                    }
                    if (typeof fov === 'number' && this.camera) {
                        let vfov = fov;
                        if (isHorizontalFov) {
                            const a = aspect || (window.innerWidth / window.innerHeight);
                            const vfovRad = 2 * Math.atan(Math.tan((fov * Math.PI / 180) / 2) * (1 / a));
                            vfov = vfovRad * 180 / Math.PI;
                        }
                        if (!Number.isNaN(vfov)) {
                            this.camera.fov = vfov;
                            this.camera.updateProjectionMatrix();
                        }
                    }
                } else if (data.type === 'splatSceneAabb' && data.payload) {
                    const { bboxMin, bboxMax, center, halfExtents, groundY } = data.payload;
                    // 记录 AABB 信息，便于其他逻辑使用
                    this.splatAabb = { bboxMin, bboxMax, center, halfExtents, groundY };
                    // 更新当前场景的角色生成点的高度到地面
                    if (this.currentScene) {
                        const prev = this.currentScene.characterSpawnPoint || { x: 0, y: 0, z: -2 };
                        const nextY = (typeof groundY === 'number') ? groundY : prev.y;
                        this.currentScene.characterSpawnPoint = { x: prev.x, y: nextY, z: prev.z };
                    }
                    // 将已加载角色的Y位置即时对齐到地面
                    if (typeof groundY === 'number') {
                        try {
                            this.characterGroup.children.forEach(child => {
                                if (!child?.userData?.isCharacter) return;
                                const box = new THREE.Box3().setFromObject(child);
                                const minY = Number.isFinite(box?.min?.y) ? box.min.y : child.position.y;
                                const delta = groundY - minY;
                                if (!Number.isNaN(delta)) {
                                    child.position.y += delta;
                                }
                            });
                        } catch (e) {
                            console.warn('对齐角色到地面时出错:', e);
                        }
                    }
                    // 分发事件，便于外部监听
                    this.dispatchEvent('splatAabbUpdated', this.splatAabb);
                }
            } catch (e) {
                console.warn('处理 Viewer 消息失败:', e);
            }
        };
        window.addEventListener('message', this._onSplatViewerMessage);
    }

    /**
     * 销毁 Supersplat Viewer 覆盖层
     */
    destroySplatViewerOverlay() {
        // 移除消息监听，清理引用
        if (this._onSplatViewerMessage) {
            window.removeEventListener('message', this._onSplatViewerMessage);
            this._onSplatViewerMessage = null;
        }
        this.splatViewerIframe = null;

        if (this.splatViewerContainer && this.splatViewerContainer.parentNode) {
            this.splatViewerContainer.parentNode.removeChild(this.splatViewerContainer);
        }
        this.splatViewerContainer = null;
    }

    /**
     * 添加事件监听器
     * @param {string} event - 事件名称
     * @param {Function} callback - 回调函数
     */
    addEventListener(event, callback) {
        if (!this.eventListeners.has(event)) {
            this.eventListeners.set(event, []);
        }
        this.eventListeners.get(event).push(callback);
    }

    /**
     * 移除事件监听器
     * @param {string} event - 事件名称
     * @param {Function} callback - 回调函数
     */
    removeEventListener(event, callback) {
        if (this.eventListeners.has(event)) {
            const listeners = this.eventListeners.get(event);
            const index = listeners.indexOf(callback);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }

    /**
     * 分发事件
     * @param {string} event - 事件名称
     * @param {Object} data - 事件数据
     */
    dispatchEvent(event, data = {}) {
        if (this.eventListeners.has(event)) {
            this.eventListeners.get(event).forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`事件处理错误 ${event}:`, error);
                }
            });
        }
    }

    /**
     * 获取当前场景信息
     */
    getCurrentSceneInfo() {
        return {
            sceneId: this.currentSceneId,
            sceneConfig: this.currentScene,
            loadedCharacters: Array.from(this.loadedCharacters.keys()),
            isXRActive: this.webxrManager?.isXRActive || false
        };
    }

    /**
     * 销毁场景管理器
     */
    dispose() {
        this.clearCurrentScene();
        
        // 清理角色
        this.loadedCharacters.clear();
        this.characterGroup.clear();
        
        // 清理WebXR
        if (this.webxrManager) {
            this.webxrManager.cleanup();
        }

        // 清理事件监听器
        this.eventListeners.clear();

        console.log('沉浸式场景管理器已销毁');
    }

    /**
     * 淡出效果
     */
    async fadeOut() {
        return new Promise((resolve) => {
            const fadeElement = this.getFadeElement();
            fadeElement.style.opacity = '0';
            fadeElement.style.transition = 'opacity 0.3s ease-in-out';
            fadeElement.style.opacity = '1';
            
            setTimeout(resolve, 300);
        });
    }

    /**
     * 淡入效果
     */
    async fadeIn() {
        return new Promise((resolve) => {
            const fadeElement = this.getFadeElement();
            fadeElement.style.opacity = '1';
            fadeElement.style.transition = 'opacity 0.3s ease-in-out';
            fadeElement.style.opacity = '0';
            
            setTimeout(() => {
                fadeElement.style.display = 'none';
                resolve();
            }, 300);
        });
    }

    /**
     * 获取或创建淡入淡出遮罩元素
     */
    getFadeElement() {
        let fadeElement = document.getElementById('scene-fade-overlay');
        if (!fadeElement) {
            fadeElement = document.createElement('div');
            fadeElement.id = 'scene-fade-overlay';
            fadeElement.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: black;
                opacity: 0;
                pointer-events: none;
                z-index: 9999;
                display: none;
            `;
            document.body.appendChild(fadeElement);
        }
        fadeElement.style.display = 'block';
        return fadeElement;
    }
}